if and else¶

NOTES

Today we're going to look at some more of the fundamental tools in programming.

🎨 if¶

red_dots.py¶

Turn the red dots into blue dots.

NOTES

  • Step through red_dots.py
  • Look at control flow

    • When does the if block run? When is it skipped?
  • Comment on event stream pattern: the outer loop moves Bit along towards a goal, while the if handles events that come up along the way.

🎨 else¶

more_red_dots.py¶

Turn the red into blue and the empty spaces into green.

NOTES

  • Step through
  • When is the if block run? When is the else block run?
  • Note the exclusivity of the two blocks

🎨 elif¶

turns.py¶

  • While Bit is not blocked, move forward
  • If the square is red, turn left
  • If the square is green, turn right
  • Otherwise, paint the square blue

NOTES

  • Step through
  • Show that elif block checks conditions
  • Show that else block doesn't check a condition
  • All blocks are exclusive

Holes 👩🏼‍🎨¶

holes.py¶

Bit is in the pipes, and the pipes have holes. Bit's job is to mark where the holes are so someone else can fix them.

  • Mark holes on the right with red
  • Mark holes on the left with green
  • Otherwise paint blue

NOTES

Draw it out! Give the students time to discuss how they would solve this.

Demonstrate general strategy: how we can use a while to move Bit to the end goal and use if to handle events along the way. Event stream pattern

Errors:

  • Mix left and right
  • Don't put blue in elif (put it outside the if/else control)
  • First square/last square

Explore:

  • move-then-ifblock, ifblock-then-move

Fly 👩🏾‍🎨¶

fly.py¶

Bit is out flying around.

When Bit finds a blue square, he turns left.

When Bit finds a green square, he turns right.

When Bit finds a red square, he stops.

NOTES

Draw it out!

Errors: how do you identify and fix them?

  • Turn right on blue, left on green (runs into wall after wandering)
  • While front_clear() instead of not is_red() (misses red square)
  • Else instead of elif (turns on blank square)
  • Move in the else block (infinite loop)

Does it matter if you move-then-turn vs turn-then-move?

Key Ideas¶

  • if, else, and elif
  • event stream pattern:
    • handle specific events that come up while moving towards a goal
      • outer while with inner if
  • Boundary conditions